package bing.commons.sql;

import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class PostgresConnection {
	
    private static PostgresConnection instance=null;  
    private static ComboPooledDataSource cpds=new ComboPooledDataSource(true);   
      
    
    private void init(){ 
    	
   		Properties props = new Properties();
    	try {
    		InputStream ins = this.getClass().getResourceAsStream("postgresConfig.properties");
        	//InputStream ins = Object.class.getResourceAsStream("/postgresConfig.properties");
        	props.load(ins);
			ins.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			System.err.println("Error occurred reading postgresConfig file...");
		}
    	
    	
        //cpds.setDataSourceName("mydatasource");  
        cpds.setJdbcUrl(props.getProperty("jdbcUrl"));  
        try {  
            cpds.setDriverClass(props.getProperty("driverClass"));  
        } catch (PropertyVetoException e) {  
            e.printStackTrace();  
        }  
        cpds.setUser(props.getProperty("user"));  
        cpds.setPassword(props.getProperty("password"));
        cpds.setMaxPoolSize(Integer.valueOf(props.getProperty("maxPoolSize")));  
        cpds.setMinPoolSize(Integer.valueOf(props.getProperty("minPoolSize")));  
        cpds.setAcquireIncrement(Integer.valueOf(props.getProperty("acquireIncrement")));  
        cpds.setInitialPoolSize(Integer.valueOf(props.getProperty("initialPoolSize")));  
        cpds.setMaxIdleTime(Integer.valueOf(props.getProperty("maxIdleTime")));  
    
        cpds.setDescription(DBType.POSTGRESQL);
    }  
      
    private PostgresConnection(){
    	init();
    }  
      
    public static PostgresConnection getInstance(){  
    	if(instance==null){
    		instance=new PostgresConnection();
    	}
        return instance;  
    }  
      
    public  Connection  getConnection(){  
        try {  
            return cpds.getConnection();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
        return null;  
    }
    public String getDBType(){
    	return cpds.getDescription();
    }
    
    //数据库类型
    class DBType {

    	public static final String POSTGRESQL="postgresdb";
    	public static final String ORACLE="oracledb";
    }
}
